package com.liang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liang.pojo.User;
import com.liang.utils.JsonUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//@Controller
@RestController
public class JsonController {

    //@ResponseBody 搭配@Controller使用，不会跳转视图解析器，而是返回字符串
    @RequestMapping("/j1")
    public String test() throws JsonProcessingException {
        //创建一个对象
        User user = new User("ccb",23,"女");

        //jackson  ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        String str = mapper.writeValueAsString(user);
        return str;
    }

    @RequestMapping("/j2")
    public String test2() throws JsonProcessingException {
        User user1 = new User("ccb1",23,"女");
        User user2 = new User("ccb2",24,"女");
        User user3 = new User("ccb3",25,"女");
        User user4 = new User("ccb4",26,"女");

        List<User> users = new ArrayList<User>();
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);


        return JsonUtils.getJson(users);
    }

    @RequestMapping("/j3")
    public String test3() throws JsonProcessingException {
        //方法一：使用时间戳
        Date date = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ObjectMapper mapper = new ObjectMapper();

        String str = mapper.writeValueAsString(sdf.format(date));
        return str;
    }

    @RequestMapping("/j4")
    public String test4(){
        Date date = new Date();
        return JsonUtils.getJson(date,"yyyy-MM-dd HH:mm:ss");
    }
}
